<?php

namespace app\admin\controller;

use think\Lang;
use think\Session;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Casue extends AdminControl
{
    const EXPORT_SIZE = 1000;

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/refund.lang.php');
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/vrorder.lang.php');
        //向模板页面输出退款退货状态
        $this->getRefundStateArray();
    }

    public function reason()
    {
        $refundreturn_model = model('casue');
        $condition = array();

        if (trim(input('param.title'))) {
            $title_name = input('param.title');
            $condition['info'] = array('like', "%$title_name%");
        }

        $type = intval(input('param.type'));
        if ($type) {
            $condition['type'] = $type;
        }

        $status = intval(input('param.status'));
        if ($status) {
            if ($status == 2) {
                $condition['status'] = 0;
            } else {
                $condition['status'] = $status;
            }
        }
        /** 新增限制条件
         * */
        $condition['is_del'] = 0;
        $reason_list = $refundreturn_model->getReasonList($condition, 10);

        $this->assign('reason_list', $reason_list);
        $this->assign('show_page', $refundreturn_model->page_info->render());

        $this->assign('title_name', input('param.title'));
        $this->assign('type', $type);
        $this->assign('status', $status);

        $this->setAdminCurItem('reason');
        return $this->fetch('reason');
    }

    /**
     * 更换审核
     */
    public function change()
    {
        $order_model = model('service');
        $condition = array();

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['order_sn'] = $order_sn;
        }

        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '1', '2'))) {
            $condition['order_state'] = $order_state;
        }

        $order_type = input('param.order_type');
        if (in_array($order_type, array('1', '2', '3', '4'))) {
            $condition['order_type'] = $order_type;
        }


        $order_list = $order_model->getapp_ChangeList($condition, 10);
        $this->assign('reason_list', $order_list);

        $this->assign('show_page', $order_model->page_info->render());

        $this->assign('filtered', $condition ? 1 : 0);

        $this->assign('order_type', ['1' => '安装', '2' => '维修', '3' => '移机', '4' => '保养']);
        $this->assign('order_state', ['0' => '待审核', '1' => '审核通过', '2' => '审核失败']);
        $this->setAdminCurItem('change');
        return $this->fetch('change');
    }

    /**
     * 取消审核
     */
    public function cancel()
    {
        $order_model = model('service');
        $condition = array();

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['order_sn'] = $order_sn;
        }

        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '1', '2'))) {
            $condition['order_state'] = $order_state;
        }

        $order_type = input('param.order_type');
        if (in_array($order_type, array('1', '2', '3', '4'))) {
            $condition['order_type'] = $order_type;
        }


        $order_list = $order_model->getapp_CancelList($condition, 10);
        $this->assign('reason_list', $order_list);

        $this->assign('show_page', $order_model->page_info->render());

        $this->assign('filtered', $condition ? 1 : 0);

        $this->assign('order_type', ['1' => '安装', '2' => '维修', '3' => '移机', '4' => '保养']);
        $this->assign('order_state', ['0' => '待审核', '1' => '审核通过', '2' => '审核失败']);
        $this->setAdminCurItem('cancel');
        return $this->fetch('cancel');
    }

    /**
     * 系统处理审核  更换
     * @throws
     */
    public function change_state()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error('操作失败');
        }
        $order_model = model('service');
        $order_info = $order_model->getServiceOrderInfo($order_id);
        if (!request()->isPost()) {
            $order_id = intval(input('param.order_id'));
            $change_id = intval(input('param.change_id'));

            $change_info = db('s_order_change')->where(['change_id' => $change_id])->find();

            if ($order_id <= 0) {
                $this->error(lang('miss_order_number'));
            }
            $order_mechanics = db('s_order_mechanic')
                ->alias('s')
                ->join('fuwu_personal p', 's.merid = p.id')
                ->field('s.*,p.name,p.phone')
                ->where('order_id', $order_id)
                ->order('s.id', 'desc')
                ->select();
            $appends = db('s_order_append')
                ->where('order_id', $order_id)
                ->select();
            foreach ($appends as $key => $value) {
                $appends[$key]['hours_total'] = $value['add_hours'] * $value['payper_hour'];
            }

            $this->assign('change_info', $change_info);
            $this->assign('appends', $appends);
            $this->assign('order_mechanics', $order_mechanics);
            $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '审核通过，待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已接单', '9' => '派单中']);
            $this->assign('son_order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '支付完成', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已接单', '9' => '派单中']);
            $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '移机单', '4' => '保养单']);
            $this->assign('order_info', $order_info);
            $this->assign('status', ['0' => '未接单', '1' => '已接单', '2' => '已拒单', '3' => '已完成', '4' => '已取消', '5' => '待派单', '6' => '已更换']);
            $this->assign('appendStatus', ['1' => '待支付', '2' => '已支付', '3' => '已取消', '4' => '已作废']);

            return $this->fetch('change_state');
        } else {
            $change_id = intval(input('param.change_id'));
            if ($change_id <= 0) {
                $this->error('操作失败');
            }
            $status = intval(input('param.status'));

            $data['invoice_operation']  = Session::get('admin_id'); // 处理人
            $data['invoice_operation_name']  = Session::get('admin_name'); // 处理人
            $data['invoice_operation_time']  = time(); // 处理人

            if ($status == 1) {
                #审核成功,结算服务人员的金额
                $data['status']  = '1';
                $s_order_info =  db('s_order')->where(['order_id' => $order_id])->find();

                $service_info = db('fuwu_personal')->where(['id' => $s_order_info['assign_mechanic_id']])->find();
                $service_money = $service_info['money'] + input('money');
                db('fuwu_personal')->where(['id' => $s_order_info['assign_mechanic_id']])->update(['money' => $service_money]);
                
                db('s_order_mechanic')->where(['order_id' => $order_id, 'merid' => $s_order_info['assign_mechanic_id']])->data(['money' => input('money'),'status'=>6])->update();
                #计算总的补贴金额
                $subsidy_price = $s_order_info['subsidy_price'] + input('money');
                db('s_order')->where(['order_id' => $order_id])->update(['order_state' => 3, 'service_state' => 0, 'assign_mechanic_id' => 0, 'is_mechanic_change' => 0,'subsidy_price'=>$subsidy_price]);

                

                #通知内容
                $member_info = db('member')->where(['member_id' => $order_info['member_id']])->find();
                $notif_data = [
                    'order_id' =>  $order_id,
                    'notif_title' => '服务单通知',
                    'notif_content' =>  '您的申请的更换服务人员已审核完成，正在为您重新派单！',
                    'member_id' => $order_info['member_id'],
                    'member_name' => $order_info['member_name'],
                ];
                model('points')->saveAfficeslog(2, 0, $notif_data); #客户
                pushMessageToSingle('服务单通知', $member_info['clientid'], '您的申请的更换服务人员已审核完成，正在为您重新派单！');
            } else {
                #审核失败
                $data['fail_reason']  = input('post.no_content');
                $data['status']  = '2';
                db('s_order')->where(['order_id' => $order_id])->update(['is_mechanic_change' => 0]);
            }
            $res = db('s_order_change')->where('change_id', $change_id)->data($data)->update();


            if (!$res) {
                dsLayerOpenSuccess('操作失败');
            } else {
                dsLayerOpenSuccess('操作成功');
            }
        }
    }
    /**
     * 系统处理审核 取消
     * @throws
     */
    public function cancel_state()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error('操作失败');
        }
        $order_model = model('service');
        $order_info = $order_model->getServiceOrderInfo($order_id);
        if (!request()->isPost()) {
            $order_id = intval(input('param.order_id'));
            $cancel_id = intval(input('param.cancel_id'));

            $cancel_info = db('s_order_cancel')->where(['cancel_id' => $cancel_id])->find();

            if ($order_id <= 0) {
                $this->error(lang('miss_order_number'));
            }
            $order_mechanics = db('s_order_mechanic')
                ->alias('s')
                ->join('fuwu_personal p', 's.merid = p.id')
                ->field('s.*,p.name,p.phone')
                ->where('order_id', $order_id)
                ->order('s.id', 'desc')
                ->select();
            $appends = db('s_order_append')
                ->where('order_id', $order_id)
                ->select();
            foreach ($appends as $key => $value) {
                $appends[$key]['hours_total'] = $value['add_hours'] * $value['payper_hour'];
            }

            $this->assign('cancel_info', $cancel_info);
            $this->assign('appends', $appends);
            $this->assign('order_mechanics', $order_mechanics);
            $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '审核通过，待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已接单', '9' => '派单中']);
            $this->assign('son_order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '支付完成', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已接单', '9' => '派单中']);
            $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '移机单', '4' => '保养单']);
            $this->assign('order_info', $order_info);
            $this->assign('status', ['0' => '未接单', '1' => '已接单', '2' => '已拒单', '3' => '已完成', '4' => '已取消', '5' => '待派单', '6' => '已更换']);
            $this->assign('appendStatus', ['1' => '待支付', '2' => '已支付', '3' => '已取消', '4' => '已作废']);

            return $this->fetch('cancel_state');
        } else {
            $cancel_id = intval(input('param.cancel_id'));
            if ($cancel_id <= 0) {
                $this->error('操作失败');
            }
            $status = intval(input('param.status'));

            $data['invoice_operation']  = Session::get('admin_id'); // 处理人
            $data['invoice_operation_name']  = Session::get('admin_name'); // 处理人
            $data['invoice_operation_time']  = time(); // 处理人

            if ($status == 1) {
                #审核成功
                $data['status']  = '1';
                db('s_order')->where(['order_id' => $order_id])->update(['order_state' => 3, 'service_state' => 0, 'assign_mechanic_id' => 0, 'is_mechanic_cancel' => 0]);
                //修改服务人员状态
                $cancel_info = db('s_order_cancel')->where(['cancel_id' => $cancel_id])->find();
                db('s_order_mechanic')->where(['order_id' => $cancel_info['order_id'], 'merid' => $cancel_info['mechanic_id']])->update(['status' => 4]);

                #通知内容
                $member_info = db('member')->where(['member_id' => $order_info['member_id']])->find();
                $notif_data = [
                    'order_id' =>  $order_id,
                    'notif_title' => '服务单通知',
                    'notif_content' =>  '您的服务单服务人员已取消，正在为您重新派单！',
                    'member_id' => $order_info['member_id'],
                    'member_name' => $order_info['member_name'],
                ];
                model('points')->saveAfficeslog(2, 0, $notif_data); #客户
                pushMessageToSingle('服务单通知', $member_info['clientid'], '您的服务单服务人员已取消，正在为您重新派单！');

                $fuwu_info = db('fuwu_personal')->where(['id'=>$cancel_info['member_id']])->find();
                $notif_data = [
                    'order_id' =>  $order_id,
                    'notif_title' => '服务单通知',
                    'notif_content' =>  '您申请的取消服务单已审核',
                    'member_id' => $fuwu_info['id'],
                    'member_name' => $fuwu_info['name'],
                ];
                model('points')->saveAfficeslog(2, 1, $notif_data); #客户
                pushMessageToSingle('服务单通知', $fuwu_info['clientid'], '您申请的取消服务单已审核');
            } else {
                #审核失败
                $data['fail_reason']  = input('post.no_content');
                $data['status']  = '2';
                db('s_order')->where(['order_id' => $order_id])->update(['is_mechanic_cancel' => 0]);
            }
            $res = db('s_order_cancel')->where('cancel_id', $cancel_id)->data($data)->update();

            if (!$res) {
                dsLayerOpenSuccess('操作失败');
            } else {
                dsLayerOpenSuccess('操作成功');
            }
        }
    }

    /*
      大订单获取小订单列表
     */
    public function show()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $order_model = model('service');
        $order_info = $order_model->getServiceOrderInfo($order_id);
        $order_mechanics = db('s_order_mechanic')
            ->alias('s')
            ->join('fuwu_personal p', 's.merid = p.id')
            ->field('s.*,p.name,p.phone')
            ->where('order_id', $order_id)
            ->order('s.id', 'desc')
            ->select();
        $appends = db('s_order_append')
            ->where('order_id', $order_id)
            ->select();
        foreach ($appends as $key => $value) {
            $appends[$key]['hours_total'] = $value['add_hours'] * $value['payper_hour'];
        }
        //订单变更日志
        //        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        //        $this->assign('order_log', $log_list);
        $this->assign('appends', $appends);
        $this->assign('order_mechanics', $order_mechanics);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '审核通过，待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已接单', '9' => '派单中']);
        $this->assign('son_order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '支付完成', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已接单', '9' => '派单中']);
        $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '移机单', '4' => '保养单']);
        $this->assign('order_info', $order_info);
        $this->assign('status', ['0' => '未接单', '1' => '已接单', '2' => '已拒单', '3' => '已完成', '4' => '已取消', '5' => '待派单', '6' => '已更换']);
        $this->assign('appendStatus', ['1' => '待支付', '2' => '已支付', '3' => '已取消', '4' => '已作废']);

        return $this->fetch('show');
    }

    /**
     * 新增更换原因
     */
    public function add_reason()
    {
        $refundreturn_model = model('casue');
        if (request()->post()) {
            $reason_array = array();
            $reason_array['info'] = input('post.info');
            $reason_array['sort'] = intval(input('post.sort'));
            $reason_array['type'] = intval(input('post.type'));
            $reason_array['status'] = intval(input('post.status'));
            $reason_array['created_at'] = date('Y-m-d H:i:s', time());
            $reason_array['updated_at'] = date('Y-m-d H:i:s', time());
            //p($reason_array);die;
            $state = $refundreturn_model->addReason($reason_array);
            if ($state) {
                $this->log('新增更换原因，编号' . $state);
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                dsLayerOpenSuccess('添加失败');
            }
        }
        return $this->fetch('add_reason');
    }
    /**
     * 编辑更换原因
     *
     */
    public function edit_reason()
    {
        $refundreturn_model = model('casue');
        $condition = array();
        $condition['id'] = intval(input('param.reason_id'));
        $reason_list = $refundreturn_model->getReasonList($condition);
        $reason = $reason_list[$condition['id']];
        if (request()->post()) {
            $reason_array = array();
            $reason_array['info'] = input('post.info');
            $reason_array['sort'] = intval(input('post.sort'));
            $reason_array['status'] = intval(input('post.status'));
            $reason_array['type'] = intval(input('post.type'));
            $reason_array['updated_at'] = date('Y-m-d H:i:s');
            $state = $refundreturn_model->editReason($condition, $reason_array);
            if ($state) {
                $this->log('编辑更换原因，编号' . $condition['id']);
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                $this->error(lang('ds_common_save_fail'));
            }
        }
        $this->assign('reason', $reason);
        return $this->fetch('edit_reason');
    }

    /**
     *  退换货理由上下架
     */

    public function status()
    {
        $id = trim(input('param.id'));
        $status = trim(input('param.status'));
        $info = db('casue')->where('id', $id)->where('is_del', 0)->find();
        if ($status == 0) {
            #操作下架 判断是否是最后一条
            $count = db('casue')->where('status', 1)->where('is_del', 0)->count();
            if ($count == 1) {
                ds_json_encode(10001, '不能停用最后一条原因');
            }
        }
        if (empty($id)) {
            ds_json_encode(10001, '操作失败');
        }

        if ($status == $info['status']) {
            ds_json_encode(10001, '操作失败');
        }
        $data = array();
        $data['status'] = $status;
        $rs = db('casue')->where('id', $id)->data($data)->update();
        if ($rs) {
            $this->log(lang('ds_del') . '退换货理由上下架' . '[ID:' . $id . ']');
            ds_json_encode(10000, '操作成功');
        } else {
            ds_json_encode(10001, '操作失败');
        }
    }

    /**
     * 删除更换原因
     *
     */
    public function del_reason()
    {
        $reason_id = input('param.reason_id');
        if (empty($reason_id)) {
            ds_json_encode(10001, '操作失败');
        }
        $info = db('casue')->where('is_del', 0)->where('id', $reason_id)->find();
        if (empty($info)) {
            ds_json_encode(10001, '操作失败');
        }
        if ($info['status'] == 1) {
            ds_json_encode(10001, '请先停用');
        }
        #判断是否是最后一条
        $count = db('casue')->count();
        if ($count == 1) {
            ds_json_encode(10001, '不能删除该最后一条原因');
        }
        $rs = db('casue')->where('id', $reason_id)->data(['is_del' => 1])->update();
        if ($rs) {
            $this->log('删除更换原因，编号' . $reason_id);
            ds_json_encode('10000', lang('ds_common_del_succ'));
        } else {
            ds_json_encode('10001', lang('ds_common_del_fail'));
        }
    }

    function getRefundStateArray($type = 'all')
    {
        $state_array = array(
            '1' => lang('refund_state_confirm'), '2' => lang('refund_state_yes'), '3' => lang('refund_state_no')
        ); //卖家处理状态:1为待审核,2为同意,3为不同意
        $this->assign('state_array', $state_array);

        $admin_array = array(
            '1' => lang('admin_state_1'), '2' => lang('admin_state_2'), '3' => lang('admin_state_3')
        ); //确认状态:1为买家或卖家处理中,2为待平台管理员处理,3为退款退货已完成
        $this->assign('admin_array', $admin_array);

        $state_data = array(
            'seller' => $state_array, 'admin' => $admin_array
        );
        if ($type == 'all') {
            return $state_data; //返回所有
        }
        return $state_data[$type];
    }

    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'change', 'text' => '更换人员审核', 'url' => url('Casue/change')
            ),
            array(
                'name' => 'cancel', 'text' => '取消订单审核', 'url' => url('Casue/cancel')
            ),
            array(
                'name' => 'reason', 'text' => '服务单原因管理', 'url' => url('Casue/reason')
            ),

        );
        if (request()->action() == 'reason' || request()->action() == 'change' || request()->action() == 'cancel') {
            $menu_array[] = [
                'name' => 'add_reason', 'text' => lang('add_reason'), 'url' => "javascript:dsLayerOpen('" . url('Casue/add_reason') . "','" . lang('add_reason') . "')"
            ];
        }
        return $menu_array;
    }
}
